#include "FileReceiver.h"
#include "ConfigManager.h"

FileReceiver::FileReceiver()
{
}

FileKey FileReceiver::GetKey()
{
	return _key;
}

void FileReceiver::OnInitialization()
{
	qDebug() << "FileReceiver::OnInitialization()";
	_request = false;
	_size = 0;
}

void FileReceiver::OnReadStream(const char *s, int len)
{
	qDebug() << "FileReceiver() : OnReadStream()..";
	if (!_request)
	{
		QByteArray request(s);
		QByteArray reply = "NO\n";
		if (state() == QAbstractSocket::ConnectedState)
		{
			request.remove(0, request.indexOf(';')+1);
			_fileName = request.mid(0, request.indexOf(';'));
			request.remove(0, request.indexOf(';')+1);
			_size = request.left(request.indexOf(';')).toLongLong();

			_fp = fopen(QString(CONFIG_MANAGER->GetDownloadPath() + _fileName).toAscii().data(), "wb");
			if (_fp != NULL)
				reply = "OK\n";
		}
		if (write(reply) == -1)
			emit sigError(_key, "FileReceiver : OnReadStream() : write failed");
		else
		{
			_request = true;
			SetKey(_addr, _fileName);
			qDebug() << "FileRecever::OnReadStream() : reply - " << reply;
			emit sigStarted(_key, _size);
		}
	}
	else
	{
		int wByte = (int)fwrite(s, 1, len, _fp);
		if (wByte != -1 && wByte <= len)
			emit sigFileReceived(_key, wByte);
		else
			emit sigError(_key, "FileReceiver : OnReadStream() : fwrite failed");
	}
}

void FileReceiver::SetKey(QHostAddress addr, QString fileName, Mode mode)
{
	_key.Set(fileName, addr, mode);
}

void FileReceiver::OnDisconnected()
{
	_request = false;
	fclose(_fp);
	emit sigComplete(_key);
}
